package com.jz.community.moduleshoppingguide.search.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jz.community.basecomm.base.BaseHtml5Activity;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.base.BaseX5WebActivity;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.task.ITaskCallbackListener;
import com.jz.community.basecomm.utils.CommUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.commview.view.widget.FlowLayout;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.nearshop.ui.adapter.SearchHotWordAdapter;
import com.jz.community.moduleshoppingguide.search.bean.SearchHotKeyWordInfo;
import com.jz.community.moduleshoppingguide.search.task.SearchHotKeyWordTask;
import com.jz.community.moduleshoppingguide.search.task.UpdateHotSearchTask;
import com.jz.community.moduleshoppingguide.search.utils.SearchHistorySpUtils;
import com.qmuiteam.qmui.widget.QMUIFloatLayout;

import java.util.ArrayList;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * Created by Tony.Fan on 2018/6/1 14:15
 * 搜索
 */
@Route(path = RouterIntentConstant.SEARCH)
public class SearchActivity extends BaseMvpActivity {

    @BindView(R2.id.search_back)
    ImageView searchBack;
    @BindView(R2.id.search_delete)
    ImageView searchDelete;
    @BindView(R2.id.search_edit)
    EditText searchEdit;
    @BindView(R2.id.search_rl)
    RelativeLayout searchRl;
    @BindView(R2.id.search_btn)
    TextView searchBtn;
    @BindView(R2.id.search_toolbar)
    Toolbar searchToolbar;
    @BindView(R2.id.search_flow)
    FlowLayout searchFlow;
    @BindView(R2.id.search_near_iv)
    ImageView searchNearIv;
    @BindView(R2.id.search_near_delete)
    ImageView searchNearDelete;
    @BindView(R2.id.search_near_rv)
    RecyclerView searchNearRv;
    @BindView(R2.id.search_history_layout)
    RelativeLayout searchHistoryLayout;
    @BindView(R2.id.search_hot_keyword_layout)
    LinearLayout searchHotKeyWordLayout;

    private SearchHotWordAdapter searchHotWordAdapter;
    private int isSearchFrom;

    @Override
    protected int getContentView() {
        return R.layout.module_shoppingguide_activity_search_new;
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(searchToolbar);
        CommUtils.showKeyBoard(this, searchEdit);
    }

    @Override
    protected void initDatas() {
        super.initDatas();

        isSearchFrom = getIntent().getIntExtra("isSearchFrom", 1);

        getSearchHotKeyWordTask();

    }

    private void getSearchHistoryData() {
        if (!Preconditions.isNullOrEmpty(SearchHistorySpUtils.getInstance().querySearchHotWord(this))) {
            SHelper.vis(searchHistoryLayout);
            handleBindHotWordAdapter(SearchHistorySpUtils.getInstance().querySearchHotWord(this));
        } else {
            SHelper.gone(searchHistoryLayout);
        }
    }

    /**
     * 获取热搜词
     */
    private void getSearchHotKeyWordTask() {
        new SearchHotKeyWordTask(this, o -> {
            SearchHotKeyWordInfo searchHotKeyWordInfo = (SearchHotKeyWordInfo) o;
            if (!Preconditions.isNullOrEmpty(searchHotKeyWordInfo) && !Preconditions.isNullOrEmpty(searchHotKeyWordInfo.get_embedded().getContent())) {
                SHelper.vis(searchFlow, searchHotKeyWordLayout);
                loadSearchHotWordInfo(searchHotKeyWordInfo.get_embedded());
            } else {
                SHelper.gone(searchFlow);
            }
        }).execute();
    }

    @SuppressLint("CheckResult")
    @Override
    protected void addListener() {
        super.addListener();
        searchEdit.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String keyWord = searchEdit.getText().toString().trim();
                String hint = searchEdit.getHint().toString().trim();
                if (!Preconditions.isNullOrEmpty(keyWord)) {
                    if (keyWord.equals("充话费") || keyWord.equals("话费") || keyWord.equals("手机充值")) {
                        startTypeActivity(3, keyWord, "", "");
                    } else {
                        startTypeActivity(2, keyWord, "", "");
                        SearchHistorySpUtils.getInstance().saveSearchHotWord(SearchActivity.this, keyWord);
                    }
                } else if (!Preconditions.isNullOrEmpty(hint)) {
                    if (hint.equals("充话费") || hint.equals("话费") || hint.equals("手机充值")) {
                        startTypeActivity(3, keyWord, "", "");
                    } else {
                        if (!Preconditions.isNullOrEmpty(keyWord)) {
                            startTypeActivity(2, keyWord, "", "");
                            SearchHistorySpUtils.getInstance().saveSearchHotWord(SearchActivity.this, keyWord);
                        } else {
                            showNormal("请输入搜索关键字");
                        }
                    }
                } else {
                    showNormal("请输入搜索关键字");
                }
            }
            return false;
        });

        searchNearDelete.setOnClickListener(v -> showDeleteDialog());

        searchBtn.setOnClickListener(v -> {
            String keyWord = searchEdit.getText().toString().trim();
            String hint = searchEdit.getHint().toString().trim();
            if (!Preconditions.isNullOrEmpty(keyWord)) {
                if (keyWord.equals("充话费") || keyWord.equals("话费") || keyWord.equals("手机充值")) {
                    startTypeActivity(3, keyWord, "", "");
                } else {
                    startTypeActivity(2, keyWord, "", "");
                    SearchHistorySpUtils.getInstance().saveSearchHotWord(SearchActivity.this, keyWord);
                }
            } else if (!Preconditions.isNullOrEmpty(hint)) {
                if (hint.equals("充话费") || hint.equals("话费") || hint.equals("手机充值")) {
                    startTypeActivity(3, keyWord, "", "");
                } else {
                    if (!Preconditions.isNullOrEmpty(keyWord)) {
                        startTypeActivity(2, keyWord, "", "");
                        SearchHistorySpUtils.getInstance().saveSearchHotWord(SearchActivity.this, keyWord);
                    } else {
                        showNormal("请输入搜索关键字");
                    }
                }
            } else {
                showNormal("请输入搜索关键字");
            }
        });

        searchBack.setOnClickListener(v -> finish());

        searchDelete.setOnClickListener(v -> searchEdit.setText(""));

        RxTextView.textChangeEvents(searchEdit)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(onTextChangeEvent -> {
                    if (!Preconditions.isNullOrEmpty(onTextChangeEvent.text().toString())) {
                        SHelper.vis(searchDelete);
                    } else {
                        SHelper.gone(searchDelete);
                    }
                });
    }

    /**
     * 加载热搜词
     *
     * @param searchHotWordInfo
     */
    private void loadSearchHotWordInfo(SearchHotKeyWordInfo.EmbeddedBean searchHotWordInfo) {
        searchEdit.setHint(searchHotWordInfo.getContent().get(0).getHotSearchWord());
        for (SearchHotKeyWordInfo.EmbeddedBean.ContentBean contentBean : searchHotWordInfo.getContent()) {
            showSearchHotWordTv(contentBean);
        }
    }

    private void handleBindHotWordAdapter(ArrayList<String> searchHotWordArr) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        searchNearRv.setLayoutManager(layoutManager);
        searchHotWordAdapter = new SearchHotWordAdapter(R.layout.module_shoppingguide_item_search_near, searchHotWordArr);
        searchHotWordAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);//加载动画
        searchNearRv.setAdapter(searchHotWordAdapter);
        searchHotWordAdapter.setOnItemClickListener((adapter, view, position) -> {
            startTypeActivity(2, searchHotWordAdapter.getData().get(position), "", "");
            getSearchHistoryData();
        });
    }

    /**
     * @param contentBean 显示热搜词
     */
    private void showSearchHotWordTv(SearchHotKeyWordInfo.EmbeddedBean.ContentBean contentBean) {
        searchFlow.addView(createTextView(contentBean.getHotSearchWord(), contentBean.getType(), contentBean.getUrl(), contentBean.getId()));
    }

    /**
     * 创建Textview
     *
     * @param btnName
     * @param type
     * @param linkvalue
     * @return
     */
    private TextView createTextView(String btnName, int type, String linkvalue, String id) {
        ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = SHelper.dp2px(this, 5);
        lp.topMargin = SHelper.dp2px(this, 5);
        lp.bottomMargin = SHelper.dp2px(this, 5);
        TextView textView = new TextView(this);
        textView.setBackgroundResource(R.drawable.border_search_gray);
        if (type == 1 || type == 3) {
            //1表示活动,3表示话费充值
            textView.setTextColor(ContextCompat.getColor(this, R.color.home_red));
        } else if (type == 2) {
            //2表示商品
            textView.setTextColor(ContextCompat.getColor(this, R.color.font_gary));
        }
        textView.setPadding(SHelper.dp2px(this, 10), 0, SHelper.dp2px(this, 10), 0);
        textView.setLayoutParams(lp);
        textView.setTextSize(14);
        textView.setText(btnName);
        addTvClick(textView, type, linkvalue, id);
        return textView;
    }

    /**
     * 热搜索词点击事件
     *
     * @param tv
     * @param type
     * @param linkvalue
     * @param id
     */
    private void addTvClick(TextView tv, int type, String linkvalue, String id) {
        tv.setOnClickListener(v -> startTypeActivity(type, tv.getText().toString().trim(), linkvalue, id));
    }

    /**
     * 跳转不同类型界面
     *
     * @param type 1、活动 2、 商品 3、话费充值
     */
    private void startTypeActivity(int type, String text, String url, String id) {
        if (type == 1) {
            Intent intent = new Intent(this, BaseX5WebActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
            bundle.putString("title", text);
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (type == 2) {
            Intent intent = new Intent(this, SearchListActivity.class);
            intent.putExtra("keyWord", text);
            intent.putExtra("isSearchFrom", isSearchFrom);
            startActivity(intent);
            SearchHistorySpUtils.getInstance().saveSearchHotWord(SearchActivity.this, text);
        } else if (type == 3) {
            RouterCommonUtils.startNoParameterActivity(RouterIntentConstant.RECHARGE_PHONE);
        }
        getUpdateHotSearchTask(id);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getSearchHistoryData();
    }

    /**
     * 更新关键字
     *
     * @param id
     */
    private void getUpdateHotSearchTask(String id) {
        new UpdateHotSearchTask(this, new ITaskCallbackListener() {
            @Override
            public void doTaskComplete(Object o) {

            }
        }).execute(id);
    }

    private void showDeleteDialog() {
        new MaterialDialog.Builder(this).title("提示").content("是否清空搜索记录！").positiveText("清空").negativeText("取消")
                .negativeColor(ContextCompat.getColor(SearchActivity.this,R.color.negative_color))
                .positiveColor(ContextCompat.getColor(SearchActivity.this,R.color.positive_color))
                .onPositive((dialog, which) -> {
                    SearchHistorySpUtils.getInstance().cleanHistory(SearchActivity.this);
                    searchHotWordAdapter.notifyDataSetChanged();
                    dialog.dismiss();
                    SHelper.gone(searchHistoryLayout);
                })
                .onNegative((dialog, which) -> dialog.dismiss())
                .show();
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }
}
